<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>简易计算器</title>
		<style type="text/css">
			.container{
				width: 500px;
				margin: 50px auto;
				border: 1px solid #000;
			}
			input{
				display: inline-block;
				width: 98%;
				font-size: 32px;				
			}
		</style>
	</head>
	<body>
		<div class="container">
			<table width="100%" style="text-align: center;">
				<tr>
					<td colspan="3"><input type="text" id="screen" value="0" disabled="disabled" style="text-align: right;"/></td>
					<td><input type="button" value="清除" id="cls"/></td>
				</tr>
				<script type="text/javascript">
					var btnStr=["789+","456-","123*","0.=/"];
					var html="";
					for(var i=0;i<btnStr.length;i++){
						console.log(btnStr[i]);
						html+="<tr>";
						for(var j=0;j<btnStr[i].length;j++){							
							html+="<td><input class='btn' type='button' value='";
							html+=btnStr[i][j];
							html+="'/></td>";
						}
						html+="</tr>";
					}
					document.write(html);
				</script>
			</table>
		</div>
		<script type="text/javascript">
			var screen=document.getElementById("screen");
			var isNew=true;
			var result=0;//计算结果
			var preOperator='+';//前一次点击的与算符
			document.body.onload=function () {
				var btns=document.getElementsByClassName("btn");
				for(var i in btns) {
					btns[i].onclick=function (e) {
						if("0123456789.".indexOf(this.value)>=0)//点击输入数值
						{
							if(isNew==true){//输入数值的第一个符号
								if(preOperator=='='){
									result=0;
									preOperator='+';
								}
								if(screen.value=='0'&&this.value=='0') return;
								if(this.value=='.')
									screen.value="0"+this.value;
								else
									screen.value=this.value;
								if(screen.value!='0')
									isNew=false;
							}
							else{//输入数值的后续符号
								if(screen.value.indexOf(".")>=0&&this.value==".")
									return;
								screen.value+=this.value;
							}
						}
						else{//点击运算符
							if(isNew==true){//连续点击运算符
								preOperator=this.value;return;
							}
							isNew=true;
							switch(preOperator){
								case "+":
									result+=(screen.value-0);
									break;
								case "-":
									result-=screen.value;
									break;
								case "*":
									result*=screen.value;
									break;
								case "/":
									result/=screen.value;
									break;
							}
							screen.value=result;
							preOperator=this.value;
						}
					}
				}
			}
			var clear=document.getElementById("cls");
			clear.onclick=function () {
				screen.value="0";
				isNew=true;
				result=0;
				preOperator='+';
			}
		</script>
	</body>
</html>
